package com.cmcc.aregister.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.model.Department;
import com.cmcc.aregister.cs.model.Doctor;
import com.cmcc.aregister.cs.model.Hospital;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.adapter.DepartmentAdapter;
import com.cmcc.aregister.ui.adapter.DoctorAdapter;
import com.cmcc.aregister.ui.adapter.HospitalAdapter;

public class ScreeningResultActivity extends ParentActivity
{
    // ------view------
    private Button top_right_btn;
    private ListView listView;
    private LinearLayout no_data_layout;

    // ------parameter------
    private List<Hospital> hospitalList = new ArrayList<Hospital>();
    private List<Doctor> doctorList = new ArrayList<Doctor>();
    private List<Department> departmentList = new ArrayList<Department>();
    private int type;
    private String area_type = "0";
    private String area_id = "";
    private String cat_no = "";
    private int currPage = 0;
    private int allPage = 0;

    // ------view------
    private HospitalAdapter hospitalAdapter;
    private DepartmentAdapter departmentAdapter;
    private DoctorAdapter doctorAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        init(R.layout.p_screening_result);
    }

    @Override
    protected void setupData()
    {
        Map<String, Object> httpMap = ((PotoalParcelable) getIntent()
            .getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE)).map;
        area_type = (String) httpMap.get(Arguments.ACTIVITY_JUMP_AREA_TYPE);
        type = (Integer) httpMap.get(Arguments.ACTIVITY_JUMP_SCREENING_TYPE);
        switch (type)
        {
        case 0:
            area_id = (String) httpMap.get(Arguments.ACTIVITY_JUMP_AREA_ID);
            sendSearchHospitalTask(area_type, area_id, "", "", "1",
                HttpAsyncTask.CACHE_TYPE_SAVE);
            break;
        case 1:
            cat_no = (String) httpMap.get(Arguments.ACTIVITY_JUMP_CAT_NO);
            sendSearchDepartmentTask(area_type, "", cat_no, "1",
                HttpAsyncTask.CACHE_TYPE_SAVE);
            break;
        case 2:
            cat_no = (String) httpMap.get(Arguments.ACTIVITY_JUMP_CAT_NO);
            sendSearchDoctorTask(area_type, "", cat_no, "1",
                HttpAsyncTask.CACHE_TYPE_SAVE);
            break;
        }
    }

    @Override
    protected void setupView()
    {
        ((ImageView) findViewById(R.id.title))
            .setBackgroundResource(R.drawable.shaixuanjieguo);
        top_right_btn = (Button) findViewById(R.id.top_right_btn);
        // top_left_image = (Button) findViewById(R.id.top_left_image);
        listView = (ListView) findViewById(R.id.listview);
        no_data_layout = (LinearLayout) findViewById(R.id.no_data_layout);
        top_right_btn.setVisibility(View.VISIBLE);
        top_right_btn.setOnClickListener(onClickListener);
        // top_left_image.setOnClickListener(onClickListener);
        listView.setOnItemClickListener(onItemClickListener);
    }

    OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3)
        {
            Intent intent = null;
            Map<String, Object> httpMap = new HashMap<String, Object>();
            PotoalParcelable potoal = new PotoalParcelable(httpMap);
            switch (type)
            {
            case 0:
                intent = new Intent(ScreeningResultActivity.this,
                    HospitalDetailActivity.class);
                httpMap.put(Arguments.ACTIVITY_JUMP_HOSPITAL,
                    hospitalList.get(position));
                httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE,
                    hospitalList.get(position).area_type);
                break;
            case 1:
                intent = new Intent(ScreeningResultActivity.this,
                    DepartmentDetailActivity.class);
                httpMap.put(Arguments.ACTIVITY_JUMP_DEPARTMENT,
                    departmentList.get(position));
                httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE,
                    departmentList.get(position).area_type);
                break;
            case 2:
                intent = new Intent(ScreeningResultActivity.this,
                    DoctorDetailActivity.class);
                httpMap.put(Arguments.ACTIVITY_JUMP_DOCTOR,
                    doctorList.get(position));
                httpMap.put(Arguments.ACTIVITY_JUMP_AREA_TYPE,
                    doctorList.get(position).area_type);
                break;
            }
            httpMap.put(Arguments.ACTIVITY_JUMP_POSITION, position);
            intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    };

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            if (id == R.id.top_right_btn)
            {
                Intent intent = new Intent(ScreeningResultActivity.this,
                    ScreeningActivity.class);
                Map<String, Object> httpMap = new HashMap<String, Object>();
                httpMap.put(Arguments.ACTIVITY_JUMP_SCREENING_TYPE, type);
                PotoalParcelable potoal = new PotoalParcelable(httpMap);
                intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        }
    };

    public void setView()
    {
        switch (type)
        {
        case 0:
            if (hospitalList.size() > 0)
            {
                if (hospitalAdapter == null)
                {
                    hospitalAdapter = new HospitalAdapter(context,
                        hospitalList, handler, currPage, allPage, false);
                    listView.setAdapter(hospitalAdapter);
                }
                else
                {
                    hospitalAdapter.list = hospitalList;
                    hospitalAdapter.currPage = currPage;
                    hospitalAdapter.allPage = allPage;
                    hospitalAdapter.notifyDataSetChanged();
                }
                showNoData(false);
            }
            else
            {
                showNoData(true);
            }
            break;
        case 1:
            if (departmentList.size() > 0)
            {
                if (departmentAdapter == null)
                {
                    departmentAdapter = new DepartmentAdapter(context,
                        departmentList, handler, currPage, allPage, false);
                    listView.setAdapter(departmentAdapter);
                }
                else
                {
                    departmentAdapter.list = departmentList;
                    departmentAdapter.currPage = currPage;
                    departmentAdapter.allPage = allPage;
                    departmentAdapter.notifyDataSetChanged();
                }
                showNoData(false);
            }
            else
            {
                showNoData(true);
            }
            break;
        case 2:
            if (doctorList.size() > 0)
            {
                if (doctorAdapter == null)
                {
                    doctorAdapter = new DoctorAdapter(context, doctorList,
                        handler, currPage, allPage, false);
                    listView.setAdapter(doctorAdapter);
                }
                else
                {
                    doctorAdapter.list = doctorList;
                    doctorAdapter.currPage = currPage;
                    doctorAdapter.allPage = allPage;
                    doctorAdapter.notifyDataSetChanged();
                }
                showNoData(false);
            }
            else
            {
                showNoData(true);
            }
            break;
        }
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg)
        {
            switch (type)
            {
            case 0:
                sendSearchHospitalTask(area_type, area_id, "", "", currPage + 1
                    + "", HttpAsyncTask.CACHE_TYPE_ACTION);
                break;
            case 1:
                sendSearchDepartmentTask(area_type, "", cat_no, currPage + 1
                    + "", HttpAsyncTask.CACHE_TYPE_ACTION);
                break;
            case 2:
                sendSearchDoctorTask(area_type, "", cat_no, currPage + 1 + "",
                    HttpAsyncTask.CACHE_TYPE_ACTION);
                break;
            }
        }
    };

    /**
     * 是否显示无数据图片
     * 
     * @param flag
     */
    public void showNoData(boolean flag)
    {
        if (flag)
        {
            listView.setVisibility(View.GONE);
            no_data_layout.setVisibility(View.VISIBLE);
        }
        else
        {
            listView.setVisibility(View.VISIBLE);
            no_data_layout.setVisibility(View.GONE);
        }
    }

    /**
     * 查询名医名院
     */
    private HttpAsyncTask sendSearchTask;

    /**
     * @param area_type 区域类别 N 0：本地 1：异地 2：所有
     * @param search_type 查询类别 N 0:搜索医院1:搜索科室2:搜索医生
     * @param area_id 医院区域 Y 本地: 7罗湖区，3317福田区，3318盐田区，3319龙岗区，8南山区，3320宝安区，3321
     *        光明新区； 异地： 1 广州，6北京，7上海，9武汉，5长沙，10成都，11西安，8重庆
     * @param unit_level 医院级别 Y
     * @param cat_no 科室分类 Y
     *        A内科；B外科；C肿瘤科；D妇产科；E儿科；F五官科；G男科；H传染科；I皮肤性病；J精神心理科K中西医结合科
     *        L生殖健康M急诊科N老年科
     * @param search_content 查询内容 Y
     * @param page 页数 N 0 表示不分页为所有，分页从1开始
     * @param pageSize 每页记录数 11 Y 默认为10
     */
    private void sendSearchTask(Map<String, String> parameterMap, int cache_type)
    {
        String searchUrl = Utils.changeUrl(
            Arguments.SERVER_URL_SEARCH_FRMOUS_HOSPITAL, parameterMap);
        if (cache_type == HttpAsyncTask.CACHE_TYPE_ACTION)
        {
            sendSearchTask = new HttpAsyncTask(HttpAsyncTask.GET,
                GlobalSetting.XML_SEARCH, searchUrl, cache_type, true);
        }
        else
        {
            sendSearchTask = new HttpAsyncTask(HttpAsyncTask.GET,
                GlobalSetting.XML_SEARCH, searchUrl, cache_type, false);
        }
        sendSearchTask.setUIHandler(sendSearchTaskHandler);
        mHttpManager.execute(sendSearchTask);
    }

    private void sendSearchHospitalTask(String area_type, String area_id,
        String unit_level, String search_content, String page, int cache_type)
    {
        logger.d("----------sendSearchHospitalTask----------" + page);
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("search_type", "0");
        parameterMap.put("area_id", area_id);
        parameterMap.put("unit_level", unit_level);
        parameterMap.put("search_content", search_content);
        parameterMap.put("page", page);
        parameterMap.put("pageSize", Arguments.pageSize);
        parameterMap.put("mobile", ConfigUtilHelper.getMobile(app));
        sendSearchTask(parameterMap, cache_type);
    }

    @SuppressWarnings("unchecked")
    Handler sendSearchTaskHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------sendSearchTaskHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    try
                    {
                        Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                        allPage = Integer.parseInt((String) httpMap
                            .get(Arguments.XML_ALLPAGE));
                        currPage = Integer.parseInt((String) httpMap
                            .get(Arguments.XML_CURRPAGE));
                        switch (type)
                        {
                        case 0:
                            List<Hospital> hospitalList_1 = (List<Hospital>) httpMap
                                .get(Arguments.XML_HOSPITAL_LIST);
                            if (currPage == 1)
                            {
                                hospitalList = hospitalList_1;
                            }
                            else
                            {
                                hospitalList.addAll(hospitalList_1);
                            }
                            break;
                        case 1:
                            List<Department> departmentList_1 = (List<Department>) httpMap
                                .get(Arguments.XML_DEPARTMENT_LIST);
                            if (currPage == 1)
                            {
                                departmentList = departmentList_1;
                            }
                            else
                            {
                                departmentList.addAll(departmentList_1);
                            }
                            break;
                        case 2:
                            List<Doctor> doctorList_1 = (List<Doctor>) httpMap
                                .get(Arguments.XML_DOCTOR_LIST);
                            if (currPage == 1)
                            {
                                doctorList = doctorList_1;
                            }
                            else
                            {
                                doctorList.addAll(doctorList_1);
                            }
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        allPage = currPage;
                    }
                }
                setView();
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                allPage = currPage;
                setView();
                break;
            }
        }
    };

    private void sendSearchDepartmentTask(String area_type,
        String search_content, String cat_no, String page, int cache_type)
    {
        logger.d("----------sendSearchDepartmentTask----------" + page);
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("search_type", "1");
        if (!"".equals(cat_no))
        {
            parameterMap.put("cat_no", cat_no);
        }
        parameterMap.put("search_content", search_content);
        parameterMap.put("page", page);
        parameterMap.put("pageSize", Arguments.pageSize);
        parameterMap.put("mobile", ConfigUtilHelper.getMobile(app));
        parameterMap.put("dep_level", "1");
        sendSearchTask(parameterMap, cache_type);
    }

    private void sendSearchDoctorTask(String area_type, String search_content,
        String cat_no, String page, int cache_type)
    {
        logger.d("----------sendSearchDepartmentTask----------" + page);
        Map<String, String> parameterMap = new HashMap<String, String>();
        parameterMap.put("area_type", area_type);
        parameterMap.put("search_type", "2");
        parameterMap.put("search_content", search_content);
        parameterMap.put("page", page);
        parameterMap.put("pageSize", Arguments.pageSize);
        if (!"".equals(cat_no))
        {
            parameterMap.put("cat_no", cat_no);
        }
        parameterMap.put("mobile", ConfigUtilHelper.getMobile(app));
        sendSearchTask(parameterMap, cache_type);
    }

    @Override
    protected void setTaskHandlerNull()
    {
        if (sendSearchTask != null)
        {
            sendSearchTask.setTaskBindingHandler(null);
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (app.changeAttention)
        {
            switch (app.type)
            {
            case 0:
                if (hospitalAdapter != null)
                {
                    Hospital hospital = hospitalList.get(app.position);
                    hospital.is_attention = app.attentioin;
                    hospitalList.set(app.position, hospital);
                    hospitalAdapter.list = hospitalList;
                    hospitalAdapter.notifyDataSetChanged();
                }
                break;
            case 1:
                if (departmentAdapter != null)
                {
                    Department department = departmentList.get(app.position);
                    department.is_attention = app.attentioin;
                    departmentList.set(app.position, department);
                    departmentAdapter.list = departmentList;
                    departmentAdapter.notifyDataSetChanged();
                }
                break;
            case 2:
                if (doctorAdapter != null)
                {
                    Doctor doctor = doctorList.get(app.position);
                    doctor.is_attention = app.attentioin;
                    doctorList.set(app.position, doctor);
                    doctorAdapter.list = doctorList;
                    doctorAdapter.notifyDataSetChanged();
                }
                break;
            }
            app.changeAttention = false;
            app.position = -1;
            app.type = -1;
            app.attentioin = "";
        }
    }
}